package com.lagou.niancheng.lagouserviceuser.service.impl;

import com.lagou.niancheng.lagou.service.common.CodeApi;
import com.lagou.niancheng.lagou.service.common.LagouConstants;
import com.lagou.niancheng.lagou.service.common.LagouException;
import com.lagou.niancheng.lagouserviceuser.common.UserErrorCode;
import com.lagou.niancheng.lagouserviceuser.common.entity.UserDO;
import com.lagou.niancheng.lagouserviceuser.common.entity.UserLoginDTO;
import com.lagou.niancheng.lagouserviceuser.common.entity.UserRegisterDTO;
import com.lagou.niancheng.lagouserviceuser.dao.UserDAO;
import com.lagou.niancheng.lagouserviceuser.service.TokenService;
import com.lagou.niancheng.lagouserviceuser.service.UserService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

/**
 * com.lagou.niancheng.lagouserviceuser.service.impl.UserServiceImpl
 *
 * @author 大犬
 * @date 2020/6/28
 */
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserDAO userDAO;

    @Resource
    private TokenService tokenService;

    @Reference
    private CodeApi codeApi;

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public void register(UserRegisterDTO userRegisterDTO) {
        // 校验用户是否已经注册
        String email = userRegisterDTO.getEmail();
        if (checkRegistered(email)) {
            throw new LagouException(UserErrorCode.EMAIL_ALREADY_EXIST);
        }
        // 校验验证码是否正确
        String verifyCode = userRegisterDTO.getVerifyCode();
        codeApi.verifyCode(email, verifyCode).check();
        // 插入用户
        UserDO userDO = new UserDO();
        userDO.setEmail(userRegisterDTO.getEmail());
        userDO.setPassword(userRegisterDTO.getPassword());
        userDAO.insertUser(userDO);
    }

    @Override
    public boolean checkRegistered(String email) {
        UserDO user = userDAO.getByEmail(email);
        return user != null;
    }

    @Override
    public String login(UserLoginDTO userLoginDTO, HttpServletResponse response) {
        String email = userLoginDTO.getEmail();
        UserDO userDO = userDAO.getByEmail(email);
        if (userDO == null) {
            throw new LagouException(UserErrorCode.USER_NOT_EXIST);
        }
        if (userDO.getPassword().equals(userLoginDTO.getPassword())) {
            // 密码正确，生成token
            String accessToken = tokenService.generateToken(email);
            // 设置到客户端cookie中
            response.addCookie(new Cookie(LagouConstants.ACCESS_TOKEN_COOKIE_NAME, accessToken));
        } else {
            throw new LagouException(UserErrorCode.PASSWORD_INCORRET);
        }
        return email;
    }


    @Override
    public String getEmail(String token) {

        return tokenService.getEmail(token);
    }

}
